package kmhc.api;

import java.util.Optional;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.support.RepositoryEntityLinks;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.Link;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import kmhc.domain.user.User;
import kmhc.form.LoginForm;
import kmhc.repository.user.UserRepository;
import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class UserController {
	
	@Autowired
	private UserRepository userRepo;
	
	@Autowired
	private RepositoryEntityLinks repositoryEntityLinks;
	
	@PostMapping(path = "/api/login")
	public ResponseEntity<EntityModel<User>> login(@RequestBody @Valid LoginForm form, HttpServletRequest request) throws ServletException {
		String username = form.getUsername();
		String password = form.getPassword();
		try {
			// try login
			request.login(username, password);
		} catch (ServletException servletException) {
			throw servletException;
		}
		// log authentication
		log.info(username + " is authenticated!");
		// return the user resource
		Optional<User> optional = userRepo.findByUsername(username);
		if (optional.isPresent()) {
			// get the resource url
			User user = optional.get();
			Link link = repositoryEntityLinks.linkToItemResource(User.class, user.getId());
			EntityModel<User> userEntity = EntityModel.of(user, link);
			return new ResponseEntity<>(userEntity, HttpStatus.OK);
		}
		throw new UsernameNotFoundException("User '" + username +"' not found!");
	}
}
